class FlashCutGenerator:
    """闪剪智能视频编辑工具类"""

    def __init__(self, config: ExtendedAIConfig):
        self.config = config
        self.fc_config = config.configs["flashcut"]

    def auto_edit_video(self,
                        input_video_path: str,
                        edit_style: str = "professional",
                        output_config: Optional[Dict] = None,
                        **kwargs) -> Dict[str, Any]:
        """智能自动视频编辑"""

        if not os.path.exists(input_video_path):
            return {
                "success": False,
                "error": "输入视频文件不存在",
                "provider": "flashcut"
            }

        # 合并输出配置
        output_settings = self.config.flashcut_defaults.copy()
        if output_config:
            output_settings.update(output_config)
        output_settings.update(kwargs)

        try:
            with open(input_video_path, 'rb') as video_file:
                files = {
                    'video': video_file,
                    'config': (None, json.dumps({
                        "model": "flashcut-standard",
                        "edit_style": edit_style,
                        "output_settings": output_settings,
                        "features": [
                            "auto_trimming",
                            "smart_subtitles",
                            "background_music",
                            "color_correction"
                        ]
                    }), 'application/json')
                }

                response = requests.post(
                    f"{self.fc_config['base_url']}/auto_edit",
                    headers={
                        "Authorization": f"Bearer {self.fc_config['api_key']}"
                    },
                    files=files,
                    timeout=600  # 10分钟超时
                )

                if response.status_code == 200:
                    result = response.json()
                    return {
                        "success": True,
                        "task_id": result.get("task_id"),
                        "status": "processing",
                        "estimated_time": result.get("estimated_time", 120),
                        "provider": "flashcut"
                    }
                else:
                    return {
                        "success": False,
                        "error": f"自动编辑失败: {response.text}",
                        "provider": "flashcut"
                    }

        except Exception as e:
            return {
                "success": False,
                "error": f"请求异常: {str(e)}",
                "provider": "flashcut"
            }

    def generate_from_script(self,
                             script: str,
                             media_materials: Optional[List[str]] = None,
                             style: str = "modern",
                             **kwargs) -> Dict[str, Any]:
        """从脚本生成完整视频"""

        payload = {
            "model": "flashcut-premium",
            "script": script,
            "style": style,
            "output_settings": {
                **self.config.flashcut_defaults,
                **kwargs
            }
        }

        if media_materials:
            payload["media_materials"] = media_materials

        try:
            response = requests.post(
                f"{self.fc_config['base_url']}/generate_from_script",
                headers={
                    "Authorization": f"Bearer {self.fc_config['api_key']}",
                    "Content-Type": "application/json"
                },
                json=payload,
                timeout=300
            )

            if response.status_code == 200:
                result = response.json()
                return {
                    "success": True,
                    "task_id": result.get("task_id"),
                    "status": "processing",
                    "provider": "flashcut"
                }
            else:
                return {
                    "success": False,
                    "error": f"脚本生成失败: {response.text}",
                    "provider": "flashcut"
                }

        except Exception as e:
            return {
                "success": False,
                "error": f"请求异常: {str(e)}",
                "provider": "flashcut"
            }

    def add_subtitles(self,
                      video_path: str,
                      subtitle_config: Optional[Dict] = None,
                      **kwargs) -> Dict[str, Any]:
        """智能添加字幕"""

        if not os.path.exists(video_path):
            return {
                "success": False,
                "error": "视频文件不存在",
                "provider": "flashcut"
            }

        subtitle_settings = {
            "font_family": "Arial",
            "font_size": 36,
            "font_color": "#FFFFFF",
            "background_color": "#00000080",
            "position": "bottom"
        }
        if subtitle_config:
            subtitle_settings.update(subtitle_config)

        try:
            with open(video_path, 'rb') as video_file:
                files = {
                    'video': video_file,
                    'config': (None, json.dumps({
                        "model": "flashcut-standard",
                        "subtitle_settings": subtitle_settings,
                        **kwargs
                    }), 'application/json')
                }

                response = requests.post(
                    f"{self.fc_config['base_url']}/add_subtitles",
                    headers={
                        "Authorization": f"Bearer {self.fc_config['api_key']}"
                    },
                    files=files,
                    timeout=300
                )

                if response.status_code == 200:
                    result = response.json()
                    return {
                        "success": True,
                        "task_id": result.get("task_id"),
                        "status": "processing",
                        "provider": "flashcut"
                    }
                else:
                    return {
                        "success": False,
                        "error": f"添加字幕失败: {response.text}",
                        "provider": "flashcut"
                    }

        except Exception as e:
            return {
                "success": False,
                "error": f"请求异常: {str(e)}",
                "provider": "flashcut"
            }

    def check_task_status(self, task_id: str) -> Dict[str, Any]:
        """检查闪剪任务状态"""
        try:
            response = requests.get(
                f"{self.fc_config['base_url']}/tasks/{task_id}",
                headers={
                    "Authorization": f"Bearer {self.fc_config['api_key']}"
                },
                timeout=30
            )

            if response.status_code == 200:
                task_data = response.json()
                status = task_data.get("status")
                result = {
                    "success": True,
                    "status": status,
                    "progress": task_data.get("progress", 0),
                    "provider": "flashcut"
                }

                if status == "completed":
                    result["video_url"] = task_data.get("video_url")
                    result["duration"] = task_data.get("duration")
                    result["file_size"] = task_data.get("file_size")
                    result["features_applied"] = task_data.get("features_applied", [])
                elif status == "failed":
                    result["error"] = task_data.get("error_message", "未知错误")

                return result
            else:
                return {
                    "success": False,
                    "error": f"状态查询失败: {response.text}",
                    "provider": "flashcut"
                }

        except Exception as e:
            return {
                "success": False,
                "error": f"查询异常: {str(e)}",
                "provider": "flashcut"
            }